package com.example.controller.collar;

import com.example.dto.business.PetBusinessDTO;
import com.example.dto.collar.FrequencyDTO;
import com.example.exception.collar.CollarNotBindException;
import com.example.pojo.Collar;
import com.example.pojo.CollarMsg;
import com.example.pojo.User;
import com.example.response.ApiResult;
import com.example.response.ErrorStatus;
import com.example.service.collar.CollarService;
import com.example.service.user.UserAuthenticationService;
import com.example.socket.server.SocketServer;
import com.example.vo.collar.CollarExploreData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Yu Wang
 */
@Api(tags = "项圈模块")
@RestController
@RequestMapping("/collar")
public class CollarController {
    @Autowired
    CollarService collarService;
    @Autowired
    UserAuthenticationService userAuthenticationService;

    @PostMapping("/binding")
    @ApiOperation("绑定项圈接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户令牌", required = true,
                    dataTypeClass = String.class, paramType = "header")
    })
    public ApiResult<CollarExploreData> userBingCollar(@RequestHeader("token") String token, @RequestBody Collar collar) {
        ApiResult<CollarExploreData> response = new ApiResult<>();
        try {
            System.out.println(SocketServer.connectingSockets);
            //硬件未连接
            if (!SocketServer.connectingSockets.containsKey(collar.getCollarId())) {
                response.setError(ErrorStatus.COLLAR_CONNECTION_NOT_FOUND);
                return response;
            }
            boolean b = collarService.bindCollarWithPet(collar);
            if (b) {
                response.setSuccess(null,"绑定成功");
            } else {
                response.setError(ErrorStatus.COLLAR_BIND_ERROR);
            }
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            response.setError(ErrorStatus.SERVER_ERROR, e.getMessage());
            return response;
        }
    }

    @GetMapping("/status/{ip}")
    @ApiOperation("获取项圈状态接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户令牌", required = true,
                    dataTypeClass = String.class, paramType = "header")
    })
    public ApiResult<CollarExploreData> etCollarStatus(@RequestHeader("token") String token, @PathVariable("ip") String ip) {
        ApiResult<CollarExploreData> response = new ApiResult<>();
        try {
            User userByToken = userAuthenticationService.login(token);
            //硬件未连接
            if (!SocketServer.connectingSockets.containsKey(ip)) {
                response.setStatus(201, "项圈未连接服务器！", null);
                //已被绑定
            } else if (SocketServer.connectingSockets.get(ip) != null) {
                if (SocketServer.connectingSockets.get(ip).equals(userByToken.getId())) {

                    response.setStatus(202, "项圈已绑定！", null);
                } else {
                    response.setError(ErrorStatus.COLLAR_ALREADY_BE_BINDED, "项圈被其他用户绑定：" + SocketServer.connectingSockets.get(ip));
                }
                //未绑定
            } else {
                Collar collar = new Collar();
                collar.setCollarId(ip);
                collarService.insertCollar(userByToken.getId(), collar);
                response.setStatus(203, "项圈新建成功！", null);
            }
            return response;
        } catch (Exception e) {
            response.setError(ErrorStatus.SERVER_ERROR, e.getMessage());
            return response;
        }
    }

    @GetMapping("/")
    @ApiOperation("获取用户所有项圈接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户令牌", required = true,
                    dataTypeClass = String.class, paramType = "header")
    })
    public ApiResult<CollarExploreData> getAllCollars(@RequestHeader("token") String token) {
        ApiResult<CollarExploreData> response = new ApiResult<>();
        try {
            User userByToken = userAuthenticationService.login(token);
            List<Collar> userAllCollars = collarService.getUserAllCollars(userByToken.getId());
            CollarExploreData data = new CollarExploreData();
            data.setCollars(userAllCollars);
            response.setSuccess(data);
            return response;
        } catch (Exception e) {
            response.setError(ErrorStatus.SERVER_ERROR, e.getMessage());
            return response;
        }
    }

    @GetMapping("/history/{ip}/{day}")
    @ApiOperation("获取用户项圈历史记录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户令牌", required = true,
                    dataTypeClass = String.class, paramType = "header")
    })
    public ApiResult<CollarExploreData> getHistoryCollarMsgs(@RequestHeader("token") String token, @PathVariable("ip") String ip, @PathVariable("day") String day) {
        ApiResult<CollarExploreData> response = new ApiResult<>();
        try {
            userAuthenticationService.login(token);
            List<CollarMsg> historyCollarMsgs = collarService.getHistoryCollarMsgs(ip, day);
            CollarExploreData data = new CollarExploreData();
            data.setCollarMsgs(historyCollarMsgs);
            response.setSuccess(data);
            ;
            return response;
        } catch (Exception e) {
            response.setError(ErrorStatus.SERVER_ERROR, e.getMessage());
            return response;
        }
    }

    @PostMapping("/setCollarMsgFrequency")
    @ApiOperation("修改获取项圈数据频率")
    public ApiResult<CollarExploreData> setCollarMsgFrequency(
            @RequestHeader("token") String token,
            @RequestBody FrequencyDTO frequencyDTO) {
        ApiResult<CollarExploreData> response = new ApiResult<>();
        try {
            collarService.setCollarMsgSendFrequency(frequencyDTO.getCollarId(), frequencyDTO.getSetFrequency());
            response.setSuccess(null);
            return response;
        } catch (Exception e) {
            response.setError(ErrorStatus.SERVER_ERROR, e.getMessage());
            return response;
        }
    }

    @GetMapping("/getPetByIp/{ip}")
    @ApiOperation("根据项圈ip拿到绑定的宠物")
    public ApiResult<CollarExploreData> getPetByIp(@PathVariable("ip") String ip) {
        ApiResult<CollarExploreData> response = new ApiResult<>();
        try {
            PetBusinessDTO petByIp = collarService.getPetByIp(ip);
            if (petByIp == null) {
                response.setError(ErrorStatus.COLLAR_NOT_FOUND);
            } else {
                CollarExploreData data = new CollarExploreData();
                data.setPet(petByIp);
                response.setSuccess(data);
            }
        } catch (CollarNotBindException e) {
            response.setError(e.getCode(), e.getMessage());

        }
        return response;
    }

    @PostMapping("/cancelBind")
    @ApiOperation("用户取消项圈与宠物的绑定")
    public ApiResult<CollarExploreData> cancelBind(@RequestHeader("token") String token,@RequestBody Collar collar){
        ApiResult<CollarExploreData> response = new ApiResult<>();
        try{
            userAuthenticationService.login(token);
            collarService.cancelBind(collar);
            response.setSuccess(null);
            return response;

        }catch (Exception e){
            e.printStackTrace();
            response.setError(ErrorStatus.SERVER_ERROR,e.getMessage());
            return response;
        }
    }

}
